//
//  ST_BTUserInfoManager.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/13.
//  Copyright © 2019 DouLei. All rights reserved.
//

import UIKit
import RealmSwift
import HandyJSON
import SwiftyUserDefaults
import NIMSDK
import SwiftyAttributes
import SwiftyJSON
import RxCocoa
import RxSwift


class ST_BTUserInfoManager: NSObject {
    //MARK: - init
    static let shared = ST_BTUserInfoManager()
    
    var heart_dance_bag:DisposeBag?
    
    private override init() {
        super.init()
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().subscribe(onNext: { loginState in
            if loginState {
                self.refresh_my_sweetheart_list()
                self.start_heart_dance()
            }else{
                self.heart_dance_bag = nil
                self.clear_sweetheart_list()
            }
        }).disposed(by: rx.disposeBag)
        
    }
    
    
    private var _currentAccountInfoMainThread:ST_BTAccountInfo?
    /**
     从数据库查询来的 对象，不能直接改变它的属性值。请使用 realm.write { }
     */
    private(set) var current_account_info:ST_BTAccountInfo?{
        get{
            if Thread.current.isMainThread{
                if _currentAccountInfoMainThread != nil{
                    return _currentAccountInfoMainThread
                }else{
                    _currentAccountInfoMainThread = get_current_user_in_current_thread()
                    return _currentAccountInfoMainThread
                }
            }
            else{
                return get_current_user_in_current_thread()
            }
        }
        set{
            _currentAccountInfoMainThread = newValue
        }
    }
    
    /**
     好友列表【主线程使用】 更新发送通知 RefreshSweetHeartNotificationKey
     */
    lazy var sweetheart_list:[ST_BTSweetheart]? = {
        
        let realm = try! Realm()
        
        let list = realm.objects(ST_BTSweetheart.self).sorted(byKeyPath: "createTime", ascending: false)
        
        return Array(list)
    }()
    
    /// App通话状态
    var app_chat_status_behavior = BehaviorRelay<ST_TIAN_MEDIA_SATE_ENUM>.init(value: .none)
    
    
    /// 门槛页面
    weak var ticket_controller:ST_TicketViewController?
    
    
    /// 用户附加属性
    var additional_attributes:ST_BTAccountAdditionalAttribute?
    
    /// 用户其他属性值更新  对应上面 additional_attributes
    var user_additional_attributes_update = BehaviorRelay<Void>(value: ())
}

extension ST_BTUserInfoManager{
    
    /// 判断用户是否功能限制
    func judge_account_frozen()->Observable<Void>{
        
        return Observable<Void>.create { observer -> Disposable in
            
            if let info = ST_BTUserInfoManager.shared.additional_attributes,info.youWereFrozen == false{
            
                observer.onNext(())
                observer.onCompleted()
                return Disposables.create()
            }
            
            let timeStr =  ST_BTUserInfoManager.shared.additional_attributes?.frozeEndTime ?? ""
            
            BTVerticalAlertViewController.presentFreezeAlert(time: timeStr)
            
            observer.onError(NSError(domain: "", code: -1, userInfo: nil))
            return Disposables.create()
        }
        
    }
    
    func get_current_user_in_current_thread()->ST_BTAccountInfo?{
        
        let realm = try! Realm()
        
        if let account = realm.objects(ST_BTAccountInfo.self).filter("accid = %@", Defaults[.currentUserID]).first{
            return account
        }
        return nil
    }
    
    
    func signOut(){
        
        //TianRegisterStepManager.shared.revertRegisterStepsAction()
        ST_RegisterMonitor.shared.clearRegister()
        
        self.clear_sweetheart_list()
        self.current_account_info = nil
        self.additional_attributes = nil
        
        Defaults[.currentUserID] = ""
        Defaults[.BTLoginSuccess] = false
        
        
        Defaults[.AttractedOldUsersIdString] = ""
        Defaults[.MatchedFeedOldUsersIdString] = ""
        
        //RegisterStepManager.shared.clearAccount()
        //RegisterStepManager.shared.step = 1
        
        ST_BTLaunchController.shared.clear_unread_msg()
        
        //                ST_RecommendHomeController.shared.normalSelected()
        //                BTProfileManager.shared.pictureFilmPath = nil
        //                BTProfileManager.shared.videoPath = nil
        ST_ConversationAdapter.shared.logout_i_m_service()
        
        self.app_chat_status_behavior.accept(.none)
        
    }
    
//    func login(account:ST_BTAccountInfo,completion:((Int)->())?) {
//
//        self.manualLogin(account: account) { (code) in
//            completion?(code)
//        }
//    }
    
    
    func login_ignore_i_m_message(account:ST_BTAccountInfo){
        
        DispatchQueue.main.async(execute: {
            
            //                    云信登录成功才清空注册信息
            ST_RegisterMonitor.shared.clearRegister()
            
            Defaults[.currentUserID] = account.accid
            
            main_thread_execute(afterDelay: 1.5) {
                Defaults[.BTLoginSuccess] = true
            }
            
            self.refresh_my_sweetheart_list()
            
            //            save to database
            let realm = try! Realm()
            try! realm.write {
                realm.add(account, update: Realm.UpdatePolicy.all)
            }
            
            if let account = realm.objects(ST_BTAccountInfo.self).filter("accid = %@", Defaults[.currentUserID]).first{
                
                self.current_account_info = account
            }
        })
        
    }
    
    
    func updateapp_chat_status(value:ST_TIAN_MEDIA_SATE_ENUM){
        
        guard let currentAccount = current_account_info else {
            app_chat_status_behavior.accept(.none)
            return
        }
        
        app_chat_status_behavior.accept(value)
        
        let cacheKey = currentAccount.accid + "_lastWidgetKey"
        
        switch value {
        case .fallInVoiceQueue,.fallInVideoQueue:
            Defaults.set(value.rawStringValue, forKey: cacheKey)
        default:
            Defaults.removeObject(forKey: cacheKey)
        }
        
    }
    
    func revert_last_status(){
        
        guard let currentAccount = current_account_info,let value = Defaults.string(forKey: currentAccount.accid + "_lastWidgetKey") else {
            
            updateapp_chat_status(value: .none)
            
            return
        }
        
        
        let status = ST_TIAN_MEDIA_SATE_ENUM.create(localstorage:value)
        
        updateapp_chat_status(value: status)
        
    }
    
    
}


